package org.pixelami.twisted
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.ObjectEncoding;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import org.pixelami.twisted.spread.pb.Protocol;

	public class TwistedSocket extends Socket
	{
		private var _protocol:Protocol;
		private var protocolName:String = "Banana";
		
		
		public function set protocol(p:Protocol):void
		{
			_protocol = p;
		}
		
		public function get protocol():Protocol
		{
			return _protocol;
		}
		
		public function TwistedSocket(host:String=null, port:int=0)
		{
			super(host, port);
			objectEncoding = ObjectEncoding.AMF0;
			//objectEncoding = ObjectEncoding.
			
		}
		
		public function initialize():void
		{
			if(_protocol)
			{
				addEventListener(Event.CLOSE, _protocol.closeHandler);
		        addEventListener(Event.CONNECT, connectHandler);
		        addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		        addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		        //addEventListener(ProgressEvent.SOCKET_DATA, _protocol.socketDataHandler);
		        addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		 	}
		 	else
		 	{
		 		throw new Error("No Protocol Defined")
		 	}
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void 
	    {
	        logger("ioErrorHandler: " + event.text);
	    }
	
	    private function securityErrorHandler(event:SecurityErrorEvent):void 
	    {
	        logger("securityErrorHandler: " + event.text);
	    }
	    
	    private function connectHandler(event:Event):void
	    {
	    	_protocol.connectionMade();
	    }
	    
	    private function socketDataHandler(event:ProgressEvent):void
	    {
	    	////trace("readBytes = "+readObject());
	    	if(protocolName == "AMF")
	    	{
		    	while(bytesAvailable)
	            {
			    	var obj:Object = readObject();
			    	trace("readBytes = "+obj);
			    	_protocol.dataReceived(obj);
	            }
	     	}
	     	else if(protocolName == "Banana")
	    	{
		    	trace(event);
		    	while(bytesAvailable)
	            {
			    	var ba:ByteArray = new ByteArray();
	            	readBytes(ba);
	            	_protocol.dataReceived(ba);
	            }
	     	}
	    }
	    
	    private function logger(str:String):void
	    {
	    	//trace(str);
	    }
	    
	    public function loseConnection():void
	    {
	    	//trace("loseConnection not Implemented");
	    }
	}
}